package com.simplegui.api;

import com.simplegui.api.handlers.TimerHandler;

public class Timer implements Runnable{
	
	private enum State{WAITING, RUNNING, STOPPED};
	
	private State state;
	private long interval;
	private Thread thread;
	private TimerHandler timerHandler;
	
	public Timer(long interval, TimerHandler timerHandler) {
		super();
		this.interval = interval;
		this.timerHandler = timerHandler;
		this.state = State.WAITING;
		this.thread = new Thread(this);
	}

	@Override
	public void run() {
		while (State.RUNNING == state){
			if (timerHandler != null){
				timerHandler.execute();
			}
			sleep();
		}
	}


	private void sleep() {
		try {
			Thread.sleep(interval);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void start(){
		if (State.WAITING == state){
			state = State.RUNNING;
			thread.start();
		}
	}
	
	public void stop(){
		if(State.RUNNING == state){
			state = State.STOPPED;
		}
	}
	
}
